package com.jiangruan.javaproject.request;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;

/**
 * @author:zhongmenglin
 * @email:3193633073@qq.com
 * @desc: 该类用于封装提供网络请求的功能代码，用于发起网络请求，并将网络请求的数据进行返回
 * @datetime:2021/12/7 15:27
 */
public class HttpUtils {
    //该函数用于实现get请求，并将请求的结果返回 path请求的资源路径 return 请求的结果
    public static String get(String path){
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String line = "";//最开始空行
        String result = "";//每次读取到以后都要累计起来的读取结果
        try {
            //Union Resource Location 统一资源定位
            URL url = new URL(path);
            URLConnection conn = url.openConnection();
            //进行连接
            conn.connect();
            //字节流
            inputStream = conn.getInputStream();
            // 字符流：按行读
            inputStreamReader = new InputStreamReader(inputStream);//字节流装换为字符流
            reader = new BufferedReader(inputStreamReader);
            while((line = reader.readLine()) != null){
                result += line;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭读取流
            try {
                if(reader != null){
                    reader.close();
                }
                if(inputStreamReader != null){
                    inputStreamReader.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /*
    * 该方法用于实现发送一个post请求，并将请求的解析到返回
    * path要请求的资源路径
    * header请求头信息
    * data请求体数据
    */
    public static String post(String path, Map<String,String> header,byte[] data){
        BufferedReader reader = null;
        OutputStream outputStream = null;
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");//设置为post请求
            conn.setDoInput(true);//允许从服务端接收数据
            conn.setDoOutput(true);//允许向服务端发送数据
            //先连接
            conn.connect();
            //设置请求头
            //ContentType:application/json
            //Authorization:"Basic" + base64(用户名+密码)
            //Property属性
            //conn.setRequestProperty("ContentType","application/json");
            //conn.setRequestProperty("Authorization","Basic"+"xxx");
            if(!header.isEmpty()){//如果请求头不为空，则要将用户设置的属性
                // 设置到请求头中
                //java中如何遍历map
                Set<String> keys = header.keySet();
                //java中如何遍历set
                for(String key : keys){
                    String value = header.get("key");
                    //将拿到的key和value设置到请求头属性中
                    conn.setRequestProperty(key,value);
                }
            }
            //输出流
            OutputStream output = conn.getOutputStream();
            //将请求的数据发送出去(发送到服务端)
            output.write(data);
            output.flush();
            //接收响应数据
            conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine())!= null){
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader != null) {
                    reader.close();
                }
                if(outputStream != null) {
                    outputStream.close();
                }
            }catch (IOException e) {
                    e.printStackTrace();
            }
        }
        return result;
    }
}
